package cn.gzy.controller;

import cn.gzy.dto.DelAttention;
import cn.gzy.dto.PageBo;
import cn.gzy.dto.UpdatePasswordUser;
import cn.gzy.mapper.UserMapper;
import cn.gzy.pojo.User;
import cn.gzy.service.UserService;
import cn.gzy.util.PageUtil;
import cn.gzy.vo.Follow;
import cn.gzy.vo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/personalInfomation")
    public User personalInfo(HttpServletRequest req){
        return userService.findByUserId((Integer)req.getAttribute("id"));
    }

    @PostMapping("/followers")
    public List<Follow> followersInIndex(HttpServletRequest req){
        return userService.findFollowers((Integer)req.getAttribute("id"),1,9,null).getList();
    }
    @PostMapping("/followersOfPage")
    public Page followersOfPage(@RequestBody PageBo page, @RequestParam("key")String key, HttpServletRequest req){
        PageUtil userPage =  userService.findFollowers((Integer)req.getAttribute("id"),page.getCurrent(),page.getSize(),key);
        return new Page(userPage);
    }

    @PostMapping("/followeds")
    public List<Follow> followedsInIndex(HttpServletRequest req){
        return userService.findFollowed((Integer)req.getAttribute("id"),1,9,null).getList();
    }
    @PostMapping("/followedsOfPage")
    public Page followedsOfPage(@RequestBody PageBo page,@RequestParam("key")String key,HttpServletRequest req){
        PageUtil userPage =  userService.findFollowed((Integer)req.getAttribute("id"),page.getCurrent(),page.getSize(),key);
        return new Page(userPage);
    }
    @PostMapping("/personInfo/{userId}")
    public User personalInfo(@PathVariable("userId")Integer userId){
        return userService.findByUserId(userId);
    }

    @PostMapping("/updateAvatar")
    public Integer updateAvatar(MultipartFile avatar,HttpServletRequest req) throws IOException {
        String pathInServer = req.getServletContext().getRealPath("/statics/images/");
        if(pathInServer == null){
            pathInServer = req.getServletContext().getRealPath("/") + File.separator + "statics" + File.separator + "images" + File.separator;
            new File(pathInServer).mkdirs(); // 创建新目录
        }
        String fromFileName = avatar.getOriginalFilename();
        int index = fromFileName.lastIndexOf(46);
        String sufName = fromFileName.substring(index);
        String fileName = fromFileName.substring(0,index);
        String newName = new StringBuffer(fileName).append(new Random().nextInt(10000)).append(sufName).toString();
        avatar.transferTo(new File(pathInServer,newName));
        User user = new User();
        user.setUserId((Integer)req.getAttribute("id"));
        user.setAvatar("/statics/images/" + newName);
        return userService.updateUser(user);
    }

    @PostMapping("/updateUser")
    public Integer updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }

    @PostMapping("/updatePassword")
    public Integer updatePassword(@RequestBody UpdatePasswordUser user){
        if(user.getPassword().equals(user.getCheckPassword())){
            User u = new User(null, user.getAccount(), user.getPassword(), null, null, null, null);
            return userService.updateUserPassword(u);
        }
        return null;
    }

    @PostMapping("/delAttention")
    public Integer delAttention(@RequestBody DelAttention delAttention,HttpServletRequest req){
        Integer myId = (Integer)req.getAttribute("id");
        Integer result = 0;
        if(delAttention.getType() == 1){
            result = userService.delAttention(myId,delAttention.getId());
        }else{
            result = userService.delAttention(delAttention.getId(),myId);
        }
        return result;
    }


    @PostMapping("/register")
    public Integer register(@RequestBody User user) {
        user.setAvatar("/statics/images/49d3a54ae35f4b09a5fedeec5f75271c_15491351977109.png");
        Integer success = userService.register(user);
        if (success>0){
            return 1;
        }else {
            return 0;
        }
    }

    // 添加关注记录
    @PostMapping("/addAttention")
    public Integer addAttention(@RequestBody AddAttentionBo addAttentionBo, HttpServletRequest req) {
        Integer myId = (Integer) req.getAttribute("id"); // 获取当前用户ID
        Integer userIdToFollow = addAttentionBo.getUserIdToFollow(); // 获取要关注的用户ID

        // 调用 UserMapper 的 addAttention 方法添加关注记录
        Integer result = userMapper.addAttention(myId, userIdToFollow);

        // 根据操作结果返回相应的状态码或信息
        return result; // 通常返回1表示成功，0或null表示失败，但具体返回值需根据业务逻辑确定
    }

    // ... 其他已存在方法 ...

    // 定义 AddAttentionBo 类来接收请求参数
    public static class AddAttentionBo {
        private Integer userIdToFollow;

        // Getter 和 Setter 方法
        public Integer getUserIdToFollow() {
            return userIdToFollow;
        }

        public void setUserIdToFollow(Integer userIdToFollow) {
            this.userIdToFollow = userIdToFollow;
        }
    }

    // 检查用户名是否存在
    @GetMapping("/checkUsernameExists")
    public boolean isUsernameExists(@RequestParam("username") String username) {
        int count = userMapper.isUsernameExists(username);
        return count > 0;
    }

    // 检查电子邮件是否存在
    @GetMapping("/checkEmailExists")
    public boolean isEmailExists(@RequestParam("email") String email) {
        int count = userMapper.isEmailExists(email);
        return count > 0;
    }
    @PostMapping("/isadmin")
    public User isadmin(HttpServletRequest req){
        return userService.isadmin((Integer)req.getAttribute("id"));
    }

}
